<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>采购计划管理 - 新增/编辑</title>
    <!-- CSS文件已在主页面(index.html)中统一加载，无需在模板中重复引入 -->
</head>

<body>

    <div id="app" class="form-container">
        <div class="form-step-container">
            <div class="form-step active">
                <div class="step-number">1</div>
                <div class="step-title">基本信息</div>
            </div>
            <iconify-icon icon="ic:outline-navigate-next" class="funi-step-icon"></iconify-icon>
            <div class="form-step">
                <div class="step-number">2</div>
                <div class="step-title">项目信息</div>
            </div>
            <iconify-icon icon="ic:outline-navigate-next" class="funi-step-icon"></iconify-icon>
            <div class="form-step">
                <div class="step-number">3</div>
                <div class="step-title">附件上传</div>
            </div>
        </div>
        <div class="container-content">
            <div class="form-step-content form-step-1 active">
                <div class="form-section-title">招标信息</div>
                <div class="funi-form">
                    <form class="form-grid">
                        <div class="form-item-row">
                            <label for="planNumber" class="form-item-label">计划编号:</label>
                            <div class="form-item-value">
                                <input type="text" id="planNumber" name="planNumber" value="自动生成" readonly>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="procurementType" class="form-item-label required">采购类型:</label>
                            <div class="form-item-value">
                                <select id="procurementType" name="procurementType">
                                    <option value="施工">施工</option>
                                    <option value="货物">货物</option>
                                    <option value="服务">服务</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="biddingCategory" class="form-item-label required">招标类别:</label>
                            <div class="form-item-value">
                                <select id="biddingCategory" name="biddingCategory">
                                    <!-- Options will be dynamically loaded based on procurementType -->
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="procurementMethod" class="form-item-label required">采购方式:</label>
                            <div class="form-item-value">
                                <select id="procurementMethod" name="procurementMethod">
                                    <option value="公告比选">公告比选</option>
                                    <option value="邀请比选">邀请比选</option>
                                    <option value="竞争性磋商">竞争性磋商</option>
                                    <option value="竞争性谈判">竞争性谈判</option>
                                    <option value="询价择优">询价择优</option>
                                    <option value="单一来源">单一来源</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="budgetAmount" class="form-item-label required">采购预算金额（万元）:</label>
                            <div class="form-item-value">
                                <input type="text" id="budgetAmount" name="budgetAmount" placeholder="采购预算金额">
                            </div>

                        </div>
                        <div class="form-item-row">
                            <label for="fundSource" class="form-item-label required">资金来源:</label>
                            <div class="form-item-value">
                                <select id="fundSource" name="fundSource">
                                    <option value="自有资金">自有资金</option>
                                    <option value="政府投资">政府投资</option>
                                    <option value="其它社会资本">其它社会资本</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="biddingTime" class="form-item-label">招标时间:</label>
                            <div class="form-item-value">
                                <input type="text" id="biddingTime" name="biddingTime" placeholder="请输入" maxlength="50">

                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="procurementOrganizationMethod" class="form-item-label required">采购组织方式:</label>
                            <div class="form-item-value">
                                <select id="procurementOrganizationMethod" name="procurementOrganizationMethod">
                                    <option value="委托招标">委托招标</option>
                                    <option value="自主招标">自主招标</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row" id="agencyRow">
                            <label for="agency" class="form-item-label required">代理机构:</label>
                            <div class="form-item-value">
                                <select id="agency" name="agency">
                                    <option value="">请选择(多选)</option>
                                    <option value="代理机构A">代理机构A</option>
                                    <option value="代理机构B">代理机构B</option>
                                    <option value="代理机构C">代理机构C</option>
                                </select>

                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="annualProcurementPlan" class="form-item-label">年采购计划（万元）:</label>
                            <div class="form-item-value">
                                <input type="number" id="annualProcurementPlan" name="annualProcurementPlan"
                                    value="0.00" step="0.01">

                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="projectHandler" class="form-item-label required">项目经办人:</label>
                            <div class="form-item-value">
                                <input type="text" id="projectHandler" name="projectHandler" value="当前创建人" readonly>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="decisionDate" class="form-item-label required">立项决策日期:</label>
                            <div class="form-item-value">
                                <input type="date" id="decisionDate" name="decisionDate">
                            </div>
                        </div>
                    </form>
                </div>

                <div class="form-section-title">项目信息</div>
                <div class="funi-form">
                    <form class="form-grid">
                        <div class="form-item-row">
                            <label for="projectType" class="form-item-label required">项目类型:</label>
                            <div class="form-item-value">
                                <select id="projectType" name="projectType">
                                    <option value="依法必须招标项目">依法必须招标项目</option>
                                    <option value="非法定招标采购项目">非法定招标采购项目</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="projectOwner" class="form-item-label required">项目业主:</label>
                            <div class="form-item-value">
                                <input type="text" id="projectOwner" name="projectOwner"
                                    placeholder="由项目经办人信息自动带入，可再次配置" maxlength="50" readonly>

                            </div>
                        </div>
                        <div class="form-item-row form-item-full-width">
                            <label for="projectBasicInfo" class="form-item-label">项目基本情况:</label>
                            <div class="form-item-value">
                                <textarea id="projectBasicInfo" name="projectBasicInfo" maxlength="255"></textarea>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="secondaryCompany" class="form-item-label">所属二级公司单位:</label>
                            <div class="form-item-value">
                                <input type="text" id="secondaryCompany" name="secondaryCompany" maxlength="255"
                                    placeholder="请选择二级公司单位" readonly>
                            </div>
                        </div>
                        <div class="form-item-row">
                            <label for="remarks" class="form-item-label">备注:</label>
                            <div class="form-item-value">
                                <input type="text" id="remarks" name="remarks" maxlength="255">
                            </div>
                        </div>
                        <div class="form-item-row form-item-full-width">
                            <label for="decisionFiles" class="form-item-label">立项决策文件:</label>
                            <div class="form-item-value">
                                <input type="file" id="decisionFiles" name="decisionFiles" multiple>
                                <div class="form-item-tip">支持多附件上传</div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="form-step-content form-step-2"></div>
            <div class="form-step-content form-step-3"></div>
        </div>

        <div class="form-actions" id="formActions">
            <!-- Buttons will be dynamically loaded here -->
            <button type="button" class="button primary" onclick="nextStep()">下一步</button>
        </div>
    </div>

    <!-- JS文件已在主页面(index.html)中统一加载，无需在模板中重复引入 -->
    <script>
        /*
         * 步骤表单模板 - 集成版本
         *
         * 功能说明：
         * 1. 自动检测是否为步骤表单（通过检测 .form-step 元素数量）
         * 2. 步骤表单：使用可靠的全局函数 + onclick 事件绑定
         * 3. 非步骤表单：保持原有的简单表单逻辑
         * 4. 兼容iframe环境，确保在所有环境中稳定工作
         *
         * 使用方法：
         * - 对于步骤表单：确保第一步有 active 类，设置正确的 totalSteps
         * - 对于非步骤表单：移除 .form-step-container，使用普通表单结构
         */

        // ==================== iframe兼容的状态管理 ====================
        // 使用window对象避免变量重复声明
        window.formPageState = window.formPageState || {
            isInitialized: false,
            currentStep: 1,
            totalSteps: 3, // 默认3步，根据实际步骤数调整
            formSteps: null,
            formStepContents: null,
            formActions: null,
            isStepForm: false // 是否为步骤表单
        };

        // 页面状态重置函数
        function resetFormPageState() {
            window.formPageState.isInitialized = false;
            window.formPageState.currentStep = 1;
            window.formPageState.totalSteps = 3;
            window.formPageState.formSteps = null;
            window.formPageState.formStepContents = null;
            window.formPageState.formActions = null;
            window.formPageState.isStepForm = false;
        }

        // 兼容性变量（保持向后兼容）
        let currentStep, totalSteps, formSteps, formStepContents, formActions, isStepForm;

        // ==================== 步骤表单全局函数 ====================

        // 全局函数 - 下一步（兼容iframe环境）
        window.nextStep = function() {
            if (validateCurrentStep() && currentStep < totalSteps) {
                showStep(currentStep + 1);
            }
        };

        // 全局函数 - 上一步（兼容iframe环境）
        window.prevStep = function() {
            if (isStepForm && currentStep > 1) {
                showStep(currentStep - 1);
            }
        };

        // 全局函数 - 显示指定步骤（兼容iframe环境）
        function showStep(stepNumber) {
            if (!isStepForm) return;

            currentStep = stepNumber;

            // 确保DOM元素已加载
            if (!formSteps) {
                formSteps = document.querySelectorAll('.form-step');
                formStepContents = document.querySelectorAll('.form-step-content');
                formActions = document.getElementById('formActions');
            }

            // 更新步骤指示器
            formSteps.forEach((step, index) => {
                if (index + 1 === stepNumber) {
                    step.classList.add('active');
                } else {
                    step.classList.remove('active');
                }
            });

            // 更新步骤内容
            formStepContents.forEach((content, index) => {
                if (index + 1 === stepNumber) {
                    content.classList.add('active');
                } else {
                    content.classList.remove('active');
                }
            });

            updateButtons();
        }

        // 更新按钮（使用innerHTML生成，兼容性更好）
        function updateButtons() {
            if (!isStepForm || !formActions) {
                formActions = document.getElementById('formActions');
            }

            if (!formActions) return;

            let buttonsHtml = '';

            // 上一步按钮
            if (currentStep > 1) {
                buttonsHtml += '<button type="button" class="button" onclick="prevStep()">上一步</button>';
            }

            // 下一步或提交按钮
            if (currentStep < totalSteps) {
                buttonsHtml += '<button type="button" class="button primary" onclick="nextStep()">下一步</button>';
            } else {
                // 最后一步
                buttonsHtml += '<button type="button" class="button" onclick="saveDraft()">保存草稿</button>';
                buttonsHtml += '<button type="button" class="button primary" onclick="submitForm()">提交</button>';
            }

            formActions.innerHTML = buttonsHtml;
        }

        // 保存草稿 - 全局函数
        window.saveDraft = function() {
            alert('草稿保存成功！');
        };

        // 全局函数定义 - 确保HTML onclick可以访问
        window.submitForm = function() {
            if (validateForm()) {
                alert('提交成功！');
                // 根据实际需要调整跳转逻辑
                if (window.top && window.top.location) {
                    window.top.location.hash = '#/list-page'; // 修改为实际的列表页面路径
                }
            }
        };

        // 返回列表页 - 全局函数
        window.goBack = function() {
            if (window.top && window.top.location) {
                window.top.location.hash = '#/list-page'; // 修改为实际的列表页面路径
            }
        };

        // 当前步骤验证（可根据需求启用或禁用）
        function validateCurrentStep() {
            // 默认禁用验证，如需启用请修改此函数
            // 保留必填项的红色※标识通过CSS样式显示
            return true;
        }

        // 表单验证（可根据具体需求扩展）
        function validateForm() {
            // 在这里添加具体的验证逻辑
            return true;
        }

        // ==================== 页面初始化函数 ====================
        function initializePage() {
            // 检测是否为步骤表单
            formSteps = document.querySelectorAll('.form-step');
            formStepContents = document.querySelectorAll('.form-step-content');
            formActions = document.getElementById('formActions');

            isStepForm = formSteps.length > 0;

            if (isStepForm) {
                // 步骤表单逻辑
                totalSteps = formSteps.length;

                // 初始化第一步
                showStep(1);

                // 绑定步骤点击事件
                formSteps.forEach((step, index) => {
                    step.addEventListener('click', function() {
                        showStep(index + 1);
                    });
                });
            }

            // ==================== 业务逻辑（保持原有功能） ====================
            const procurementTypeSelect = document.getElementById('procurementType');
            const biddingCategorySelect = document.getElementById('biddingCategory');
            const procurementOrganizationMethodSelect = document.getElementById('procurementOrganizationMethod');
            const agencyRow = document.getElementById('agencyRow');
            const decisionDateInput = document.getElementById('decisionDate');

            // 只有当元素存在时才执行相关逻辑
            if (decisionDateInput) {
                // Set default decision date to current date
                const today = new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                decisionDateInput.value = `${year}-${month}-${day}`;
            }

            if (procurementTypeSelect && biddingCategorySelect) {
                const biddingCategories = {
                    '施工': ['工程类(施工/勘察/EPC/监理)'],
                    '货物': ['货物类(材料/设备/供应及安装)'],
                    '服务': ['服务类(监理/咨询/物业)'],
                    '其他': ['其他(文本输入)']
                };

                const updateBiddingCategory = () => {
                    const selectedType = procurementTypeSelect.value;
                    const categories = biddingCategories[selectedType] || [];
                    biddingCategorySelect.innerHTML = '';
                    categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category;
                        option.textContent = category;
                        biddingCategorySelect.appendChild(option);
                    });
                };

                // Initial load
                updateBiddingCategory();
                procurementTypeSelect.addEventListener('change', updateBiddingCategory);
            }

            if (procurementOrganizationMethodSelect && agencyRow) {
                const toggleAgencyVisibility = () => {
                    if (procurementOrganizationMethodSelect.value === '委托招标') {
                        agencyRow.style.display = 'flex';
                    } else {
                        agencyRow.style.display = 'none';
                    }
                };

                // Initial load
                toggleAgencyVisibility();
                procurementOrganizationMethodSelect.addEventListener('change', toggleAgencyVisibility);
            }

            // ==================== 编辑模式数据加载 ====================
            // 获取URL参数判断是否为编辑模式
            const hash = window.top ? window.top.location.hash : window.location.hash;
            const queryString = hash.split('?')[1] || '';
            const urlParams = new URLSearchParams(queryString);
            const id = urlParams.get('id');

            if (id) {
                loadFormData(id);
            }
        }

        // ==================== 兼容iframe环境的初始化 ====================
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializePage);
        } else {
            // DOM已经加载完成，立即初始化（适用于iframe环境）
            initializePage();
        }

        // ==================== 数据加载函数 ====================
        function loadFormData(id) {
            // 示例数据加载逻辑（实际使用时替换为真实的API调用）
            const dummyData = {
                planNumber: id,
                procurementType: '货物',
                biddingCategory: '货物类(材料/设备/供应及安装)',
                procurementMethod: '公告比选',
                budgetAmount: 150.00,
                fundSource: '自有资金',
                biddingTime: '2023年4季度',
                procurementOrganizationMethod: '自主招标',
                agency: ['代理机构A'], // Example for multi-select
                annualProcurementPlan: 140.00,
                projectHandler: '张三',
                decisionDate: '2023-03-10',
                projectType: '依法必须招标项目',
                projectOwner: '集团本部',
                projectBasicInfo: '这是一个测试项目基本情况描述。',
                secondaryCompany: '某二级公司',
                remarks: '这是备注信息。'
            };

            // 填充表单数据
            Object.keys(dummyData).forEach(key => {
                const element = document.getElementById(key);
                if (element) {
                    if (element.tagName === 'SELECT' && element.multiple) {
                        // 处理多选下拉框
                        Array.from(element.options).forEach(option => {
                            option.selected = dummyData[key].includes(option.value);
                        });
                    } else {
                        element.value = dummyData[key];
                    }
                }
            });

            // 触发相关的更新事件
            const procurementTypeSelect = document.getElementById('procurementType');
            const procurementOrganizationMethodSelect = document.getElementById('procurementOrganizationMethod');

            if (procurementTypeSelect) {
                procurementTypeSelect.dispatchEvent(new Event('change'));
            }
            if (procurementOrganizationMethodSelect) {
                procurementOrganizationMethodSelect.dispatchEvent(new Event('change'));
            }
        }
    </script>
</body>

</html>